import React, {useEffect, useRef, useState} from 'react';
import {Image, ScrollView, StyleSheet, Text, TextInput, View} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Images from '../../images/images';
import LinkButton from '../../components/linkButton';
import Container from '../../components/Container';
import TouchableView from '../../components/touchableView';
import {useToast} from '../../components/toast/useToast';
import {useDialog} from '../../components/dialog/useDialog';
import {getByteLength, isValidPhoneNumber} from '../../utils/common';
import BleUtil from '../../utils/bleUtil';
import {useAppStore} from '../../store/useAppStore';
import {addSatMsgCmd, delSatMsgCmd, getSatMsgCmd} from '../../utils/bleCmd';
import store from 'react-native-simple-store'
import {formatTimestamp} from '../../utils/dateUtil';
import loading from '../../components/loading/loading';
import {useLoading} from '../../components/loading/useLoading';


const MessageEdit = ()=>{
    const navigation = useNavigation()
    const route = useRoute()
    const toast = useToast()
    const loading = useLoading()
    const dialog = useDialog()

    const {data,index,no} = route.params
    const [message,setMessage] = useState('')
    const [phone,setPhone] = useState('13866668888')


    const {appState:{currentDevice,pressure},updateAppState,addMessage,deleteMessage }= useAppStore()

    useEffect(()=>{

        if(data){
            setMessage(data.message)
            setPhone(data.phone)
            navigation.setOptions({
                title:'短信详情',
                headerRight:()=>{
                    return (
                        <TouchableView
                            style={{paddingHorizontal: screen.PIXEL_20}}
                            onPress={deleteMsg}
                        >
                            <Image source={Images.delete}
                                   resizeMode={'contain'}
                                   style={{width:screen.PIXEL_30,height:screen.PIXEL_30}}
                            />
                        </TouchableView>
                    )
                }
            })
            let cmd = getSatMsgCmd(data.no )
            sendCmd(cmd)
        }


    },[])

    const deleteMsg = ()=>{
        dialog.alertConfirm('删除短信？',()=>{
            let cmd = delSatMsgCmd(data.no)
            sendCmd(cmd)
            deleteMessage(index,()=>{
                navigation.goBack()
            })
        })

    }

    const sendCmd = (cmd)=>{
        if(!currentDevice) return
        BleUtil.clearResults()
        BleUtil.write(currentDevice.id,cmd).then(()=>{
            console.log(cmd);
        }).catch(error=>{
            console.log('write error:',error);
        })
    }

    const saveMessage = ()=>{

        console.log('msglength:',getByteLength(message));
        // console.log('message',message)
        if(!message){
            toast.show('请输入短信内容')
            return
        }
        if(!phone){
            toast.show('请输入手机号')
            return
        }
        if(!isValidPhoneNumber(phone)){
            toast.show('手机号码不正确，请重新输入')
            return
        }

        if(!currentDevice){
            toast.show('请先连接设备')
            return
        }

        BleUtil.isPeripheralConnected(currentDevice.id).then(isConnected=>{
            console.log('是否连接',isConnected);
            if(isConnected){
                loading.show()
                const cmd = addSatMsgCmd(false,phone,message)

                sendCmd(cmd)

                saveToLocal()


                // BleUtil.writeWithoutResponse(currentDevice.id,cmd).then(()=>{
                //     saveToLocal()
                // }).catch(error=>{
                //     console.log('发送失败');
                // })
            }else{
                toast.show('设备已断开连接,请重新连接')
                updateAppState({
                    currentDevice:null,
                    battery:0
                })

            }
        })

    }

    const saveToLocal = ()=>{
        const createTime = formatTimestamp(new Date(),'yyyy/MM/dd hh:mm:ss')
        let msg = {message,phone,createTime,no}
        addMessage(msg)
        loading.hide()
        toast.showSuccess("同步成功")
        setTimeout(()=>{
            navigation.goBack()
        },1000)
    }


    return (
        <Container>
            <ScrollView
                contentContainerStyle={{paddingHorizontal:screen.PIXEL_30,alignItems:'center',paddingTop:screen.PIXEL_40}}
            >

                <View style={styles.phoneInputWrap}>
                    <TextInput
                        value={phone} onChangeText={setPhone}
                        maxLength={11}
                        keyboardType={'numeric'}
                        placeholder={'请输入收信手机号'}
                        style={styles.input}
                    />
                </View>


                <View style={styles.inputWrap}>
                    <TextInput
                        multiline={true} value={message} onChangeText={setMessage}
                        placeholder={'请输入卫星短信内容'} style={styles.input} maxLength={20}
                    />
                    <Text style={styles.numText}>{message.length} / 20</Text>
                </View>

                {
                    data ? (
                        <View style={styles.bottomWrap}>
                            <View style={styles.rowItem}>
                                <Text style={styles.rowItemText}>卫星终端:</Text>
                                <Text style={styles.rowItemText}>{currentDevice.name}</Text>
                            </View>
                            <View style={styles.rowItem}>
                                <Text style={styles.rowItemText}>创建账号:</Text>
                                <Text style={styles.rowItemText}>15888888888(本账号)</Text>
                            </View>
                            <View style={styles.rowItem}>
                                <Text style={styles.rowItemText}>创建时间:</Text>
                                <Text style={styles.rowItemText}>{data.createTime}</Text>
                            </View>
                        </View>
                    ) :null
                }


            </ScrollView>

            <LinkButton
                style={{marginBottom:screen.PIXEL_120,alignSelf:'center'}}
                title={data ? '返回':'保存并同步终端'}

                onPress={()=>{
                    if(data){
                        navigation.goBack()
                    }else{
                        saveMessage()
                    }
                }}
            />
        </Container>
    )
}
export default MessageEdit

const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    phoneInputWrap:{
        width:'100%',height:screen.PIXEL_90,backgroundColor:'#fff',
        borderRadius:screen.PIXEL_20,padding:screen.PIXEL_20,marginBottom:screen.PIXEL_30,
    },
    inputWrap:{
        width:'100%',height:screen.PIXEL_400,backgroundColor:'#fff',
        borderRadius:screen.PIXEL_20,padding:screen.PIXEL_20,marginBottom:screen.PIXEL_30,
    },
    input:{
        flex:1,padding:0,textAlignVertical: 'top'
    },
    numText:{
        textAlign:'right',fontSize:12,color:'#333'
    },
    tagWrap:{
        flexDirection: 'row'
    },
    tag:{
        flex:1,height:screen.PIXEL_90,backgroundColor: '#fff',flexDirection:'row',alignItems:'center'
        ,justifyContent:'space-between', borderRadius: screen.PIXEL_20,paddingHorizontal:screen.PIXEL_30
    },
    rowCenter:{
        flexDirection:'row',alignItems: 'center'
    },
    tagImg:{
        width:screen.PIXEL_30,height:screen.PIXEL_30
    },
    tagText:{
        marginLeft:screen.PIXEL_16,color:'#333',fontSize: screen.PIXEL_30
    },
    bottomWrap:{
        width:'100%',backgroundColor:'#fff',
        borderRadius:screen.PIXEL_20,padding:screen.PIXEL_20,marginTop:screen.PIXEL_30,
    },
    rowItem:{
        flexDirection:'row',justifyContent: 'space-between',alignItems:'center',marginBottom:5
    },
    rowItemText:{
        color:'#333',fontSize:13
    }
})
